/**
 * This file is part of Wireless TransFer.
 *
 *   Wireless TransFer is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *	
 *   Wireless TransFer is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with Wireless TransFer.  If not, see <http://www.gnu.org/licenses/>.
 *
 *	 Copyright (C) 2011
 *   @author prebz
 */

package com.wirelesstransfer.activity.receive;

import java.util.regex.*;

public class Authenticate implements IAuthenticate{
	
	/*
	 * It is not necessary to check the max length
	 * of either getValueCode and getValueIp because
	 * that constraint is set in the .xml file for
	 * the corresponding EditText field
	 * 
	 * In getValueCode you don't really need to check if
	 * it is a integer or not because that constraint is 
	 * set in the .xml file
	 */
	
	private Integer code;
	public static final int CODELENGTH = 6;

	/**
	 * Constructor
	 */
	public Authenticate(){
		code = -1;
	}

	/**
	 * Get the code from textField
	 * @return the value of the code
	 * 		   returns -1 if not an integer
	 * 		   returns -2 if to many/few integers
	 */
	public int getValueCode(String codeStr) {	
		if(codeStr.length() != CODELENGTH)
			code = -2;
		else {
			try {
				code = Integer.parseInt(codeStr);				
			} catch (NumberFormatException e) {
				code = -1;
			}
		}
		return code;
	}

	/**
	 * returns the ip address
	 * @return the ip address as a string if it is valid
	 * 		   if not valid returns null	 
	 */
	public String getValueIp(String ip) {
		if(isIp(ip))
			return ip;
		else
			return null;
	}

	/**
	 * check if the string is a valid ip
	 * @param ip
	 * @return true if match
	 */
	private boolean isIp(String ip){
		//the pattern checks if the string is of the form
		//xxx.xxx.xxx.xxx where the xxx is 1-3 positive integers
		Pattern p = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
		Matcher m = p.matcher(ip);
		if (m.matches())
			return true;
		else
			return false;

	}
}
